/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin		 	*/
/*	Project:	GlbLib-1.0.0			*/
/*	Author:		gong_libin			*/
/*	Date:		2016_06_01			*/
/*	File:		GlbSemTest.cpp			*/
/********************************************************/

#include "GlbSem.h"
#include "GlbShm.h"
#include <unistd.h>

using namespace GlbIpc;

#define	GLB_TEST				10

static CGlbShm sg_CShm;
static CGlbSem sg_CSem;

void GlbSemTestParent()
{
	UINT uiCount = 1;

	while (uiCount < GLB_TEST) {
		sg_CSem.GlbSemAcquire();
		sleep(1);
		sprintf((char*)sg_CShm.GlbShmGetShm(), "%d: This is GlbSemTest.\n", uiCount ++);
		sg_CSem.GlbSemRelease();
	}

	return;
}

void GlbSemTestChild()
{
	UINT uiCount = 1;

	while (uiCount < GLB_TEST) {
		sg_CSem.GlbSemAcquire();
		if (strlen((char*)sg_CShm.GlbShmGetShm()) > 0) {
			if (uiCount == (UINT)atoi((char*)sg_CShm.GlbShmGetShm())) {
				GLB_PRINT("Value: %s", (char*)sg_CShm.GlbShmGetShm());
				uiCount += 1;
			}
		}
		sg_CSem.GlbSemRelease();
	}

	return;
}

int main(int argc, char* argv[])
{
	pid_t iPid;

	if (GLB_SUCCESS == sg_CShm.GlbIpcCreate(sg_CShm.GlbIpcKey((char*)"/root", 'T'), sizeof(UCHAR) * GLB_PACKET)) {
		sg_CShm.GlbShmReset(sizeof(UCHAR) * GLB_PACKET);
		if (GLB_SUCCESS == sg_CSem.GlbIpcCreate(sg_CSem.GlbIpcKey((char*)"/root", 'S'))) {
			iPid = fork();
			if (iPid < 0) {
				GLB_ERROR("%s\n", strerror(errno));
			}
			else if (iPid > 0) {
				GlbSemTestParent();
			}
			else {
				GlbSemTestChild();
			}
			sleep(1);
			sg_CSem.GlbIpcDelete();
		}
		sg_CShm.GlbIpcDelete();
	}

	return GLB_SUCCESS;
}
